package nio;

import sun.misc.Unsafe;

import java.lang.reflect.Field;

public class UnsafeExample {

    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {

        Field theUnsafeField = Unsafe.class.getDeclaredField("theUnsafe");
        theUnsafeField.setAccessible(true);
        Unsafe unsafe = (Unsafe) theUnsafeField.get(null);
        // 分配对外内存，返回内存大小
        long size = 1024; // 内存大小
        long address = unsafe.allocateMemory(size);
        // 写入数据到堆外内存
        String dataToWrite = "Hello,this is hollis testing direct memory!";
        byte[] dataBytes = dataToWrite.getBytes();
        for (int i = 0; i < dataBytes.length; i++) {
            unsafe.putByte(address + i,dataBytes[i]);
        }
        // 从堆外内存读取数据
        byte[] dataToRead = new byte[dataBytes.length];
        for (int i = 0; i < dataBytes.length; i++) {
            dataToRead[i] = unsafe.getByte(address + i);
        }
        System.out.println(new String(dataToRead));
        // 释放堆外内存
        unsafe.freeMemory(address);
    }

}
